import './setEnvVars';
import prisma from '../lib/prisma';

beforeAll(async () => {
  await prisma.$connect();
});

beforeEach(async () => {
  const tablenames = await prisma.$queryRaw<Array<{ tablename: string }>>`
    SELECT tablename 
    FROM pg_tables
    WHERE schemaname='public'
  `;

  const tables = tablenames
    .map(({ tablename }: { tablename: string }) => tablename)
    .filter((name: string) => !name.includes('_prisma_'))
    .filter((name: string) => !name.includes('schema_migrations'));

  try {
    await prisma.$transaction([
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL DEFERRED'),
      ...tables.map((table: string) => 
        prisma.$executeRawUnsafe(`TRUNCATE TABLE "${table}" CASCADE`)
      ),
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL IMMEDIATE'),
    ]);
  } catch (error) {
    console.error('清理测试数据失败:', error);
    throw error;
  }
});

afterAll(async () => {
  await prisma.$disconnect();
});
